import util from '@/libs/util.js'
// import { getTokenApi } from '@/api/common.js'
import { wxLoginApi } from '@/api/login.js'

const state = {
	token: util.storage.get('token') || '',	// token
	phone_verify: 0, // 手机激活：已激活1；未激活0
	is_real: 0, // 姓名与头像：已设置1，未0
	is_bind_wx: 0, // 绑定微信：已绑定1，未0
	identity_verify: 0, // 身份认证：已认证1，未0
	is_login_verify: 0, // 登录验证，如通过手机登录默认已验证
	
	info: {},
	is_bind_phone: 0, // 是否绑定手机号
	name: "",	// 用户名
	phone: "",	// 手机号
	user_no: "",	// 用户编号
}

const mutations = {
	SET_TOKEN(state, token) {
		state.token = token;
		util.storage.set('token', token)
	},
	REMOVE_TOKEN(state) {
		state.token = '';
		util.storage.remove('token')
	},
	SET_USER_INFO(state, info) {
		state.info = info
		state.phone_verify = info.phone_verify || 0 // 手机激活：已激活1；未激活0
		state.is_real = info.is_real || 0 // 姓名与头像：已设置1，未0
		state.is_bind_wx = info.is_bind_wx || 0 // 绑定微信：已绑定1，未0
		state.identity_verify = info.identity_verify || 0 // 身份认证：已认证1，未0
		state.is_login_verify = info.is_login_verify || 0 // 登录验证，如通过手机登录默认已验证
		state.is_bind_phone = info.is_bind_phone || 0 // 是否绑定手机号
		state.name = info.name || ''	// 用户名
		state.phone = info.phone || ''	// 手机号
		state.user_no = info.user_no || ''	// 用户编号
	}
}

const actions = {
	getToken({ commit, dispatch, state, rootState }) {
		return new Promise(async (resolve, rejects)=> {
			const { code } = await wx.login()
			const params = {
				appid: rootState.common.appid, // 小程序appid
				code
			}
			wxLoginApi(params).then(res=> {
				commit('SET_TOKEN', res.data.access_token)
				commit('SET_USER_INFO', res.data)
				resolve(res.data.access_token)
			}).catch(err=> {
				if (err.retcode === 4066) {
					resolve('')
				}
			})
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}